package com.newtribe.net;

import java.net.DatagramSocket; 
import java.net.InetSocketAddress; 
import java.net.SocketAddress; 
import java.nio.ByteBuffer; 
import java.nio.CharBuffer; 
import java.nio.channels.DatagramChannel; 
import java.nio.channels.SelectionKey; 
import java.nio.channels.Selector; 
import java.nio.charset.Charset; 
import java.util.HashMap;
import java.util.Iterator; 
import java.util.Map;
import java.util.Set; 


public class UDPServerChannel extends Thread { 
	
	private int port =8911 ;
	
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	
	public UDPServerChannel() {
		
	}
	public UDPServerChannel(int port) {
		this.port=port;
	}
	public void run () { 
		Selector selector = null ; 
		try { 
			DatagramChannel channel = DatagramChannel.open () ; 
			DatagramSocket socket = channel.socket () ; 
			channel.configureBlocking ( false ) ; 
			socket.bind ( new InetSocketAddress ( port )) ; 

			selector = Selector.open () ; 
			System.out.println("================ start udp server :\n ln:" +port );
			channel.register ( selector, SelectionKey.OP_READ ) ; 
		} catch ( Exception e ) { 
			e.printStackTrace () ; 
		} 

		ByteBuffer byteBuffer = ByteBuffer.allocate ( 1024 ) ; 
		while ( true ) { 
			try { 
				int eventsCount = selector.select () ; 
				if ( eventsCount > 0 ) { 
					Set selectedKeys = selector.selectedKeys () ; 
					Iterator iterator = selectedKeys.iterator () ; 
					while ( iterator.hasNext ()) { 
						SelectionKey sk = ( SelectionKey ) iterator.next () ; 
						iterator.remove () ; 
						if ( sk.isReadable ()) { 
							DatagramChannel datagramChannel = ( DatagramChannel ) sk .channel () ; 
							SocketAddress sa = datagramChannel .receive ( byteBuffer ) ; 
							byteBuffer.flip () ; 

//							测试：通过将收到的ByteBuffer首先通过缺省的编码解码成CharBuffer 再输出 
							CharBuffer charBuffer = Charset.defaultCharset () .decode ( byteBuffer ) ; 
							System.out.println ( "receive message:" + charBuffer.toString ()) ; 
							byteBuffer.clear () ; 
							String echo = "This is the reply message from 服务器。" ; 

							ByteBuffer buffer = Charset.defaultCharset () .encode ( echo ) ; 
							datagramChannel.write ( buffer ) ; 

						} 
					} 
				} 
			} catch ( Exception e ) { 
				e.printStackTrace () ; 
			} 
		} 

	} 
	
	public void doStart() throws Exception {
		UDPServerChannel server =new UDPServerChannel () ;
		server.start () ; 
		//connect http server for handshake.
		
		
	}

	public static void main ( String [] args )throws Exception { 
		//start udp server
		UDPServerChannel server =new UDPServerChannel(); 
		server.doStart();
		
	} 
}  